#!/usr/bin/env python
#-*- coding:utf-8 -*-

import os
import sys
import string
import time
import MySQLdb
import simplejson
from Tools import connectMySQL
from Tools import getPid

def help():
    print '''
[usage]
  python newUserPerDay.py
[help]
  python newUserPerDay.py help
    '''

def ISOString2Time(s):
    '''
    convert a ISO format time to second
    from:2006-04-12 16:46:40 to:23123123
    '''
    return time.mktime(time.strptime(s, '%Y%m%d %X'))

def newUserPerDay(tableName, json, datetime):
    mysqldb = connectMySQL.connMySQL_stat()
    mysqldb2 = connectMySQL.connMySQL("guid")
    lasttime = ' 23:59:59'
    #day1 = '20120112'
    #day2 = '20120113'
    day2 = datetime
    #time1 = ISOString2Time(day1 + lasttime)
    time2 = ISOString2Time(datetime + lasttime)
    time1 = time2 - 24 * 60 * 60
    #print "time1 = %d" % time1
    #print "time2 = %d" % time2
    jsonVal = simplejson.loads(json)
    jsonValRes = jsonVal["results"]
    count = 0

    for result in jsonValRes:
        #count = mongodb.clientUser.find({"pid":result, "regtime":{"$gt":time1, "$lte":time2}}).count()
        cursor=mysqldb2.cursor()
        SQL = "SELECT count(*) FROM `clientUser` WHERE `pid` = \"%s\" and `regtime` > %d and `regtime` <= %d" % (result, time1, time2)
        cursor.execute(SQL)
        resultSet=cursor.fetchall()
        count = resultSet[0][0]

        try:
            cursor=mysqldb.cursor()
            SQL = "SELECT `pid` FROM `%s` WHERE `pid` = \"%s\"" % (tableName, result)
            cursor.execute(SQL)
            resultSet=cursor.fetchall()
            i = 0
            for res in resultSet:
                i+=1
            if (i == 0):
                SQL = "INSERT INTO `%s` (pid, date, pv, uv, vv, register, upload, newuser, alluser, ver)\
 VALUES (\"%s\", \"%s\", 0, 0, 0, 0, 0, %d, 0, 0)" % (tableName, result, day2, count)
                #print SQL
                cursor.execute(SQL)
            else:
                SQL = "UPDATE `%s` SET `newuser` = %d where `pid` = \"%s\" and `date` = \"%s\"" % (tableName, count, result, day2)
                #print SQL
                cursor.execute(SQL)
        except MySQLdb.Error, e:
            print e
            resultStr='failed 4001'
            print resultStr
            return resultStr

def ISOString2Time_2(s):                                                
    '''
    convert a ISO format time to second
    from:2006-04-12 16:46:40 to:23123123
    '''
    return time.mktime(time.strptime(s, '%Y-%m-%d %X'))

def main(date):
    if len(sys.argv[1]) == 4:
        help()
        exit(1)
    ISOTIMEFORMAT='%Y-%m-%d %X'
    btimeStr = time.strftime(ISOTIMEFORMAT, time.localtime())
    btime = ISOString2Time_2(btimeStr)
    print "%s Starting..." % btimeStr
    json = getPid.getMainPid_json()
    newUserPerDay("stat_day_main", json, date)
    json = getPid.getPaikePid_json()
    newUserPerDay("stat_day_paike", json, date)
    json = getPid.getChannelPid_json()
    newUserPerDay("stat_day_channel", json, date)
    json = getPid.getFactoryPid_json()
    newUserPerDay("stat_day_factory", json, date)
    etimeStr = time.strftime(ISOTIMEFORMAT, time.localtime())
    etime = ISOString2Time_2(etimeStr)
    print "%s End" % etimeStr                                               
    print "Take Time: %ds" % (etime-btime)

if __name__ == '__main__':
    main(sys.argv[1])


